package com.thinkingcoder.tcgateway.plugin.chain;

import java.util.List;

import org.springframework.web.server.ServerWebExchange;

import com.thinkingcoder.tcgateway.plugin.GatewayPlugin;

import reactor.core.publisher.Mono;

/**
 * Default GatewayPluginChan.
 */
public class DefaultGatewayPluginChain implements GatewayPluginChain {

    List<GatewayPlugin> plugins;

    int index;

    public DefaultGatewayPluginChain(List<GatewayPlugin> plugins) {
        this.plugins = plugins;
    }

    @Override
    public Mono<Void> handle(ServerWebExchange exchange) {
        return Mono.defer(() -> {
            if (index >= plugins.size()) {
                return Mono.empty();
            }
            return plugins.get(index++).handle(exchange, this);
        });
    }
}
